from collections import defaultdict


class MahjongTracker:
    def __init__(self, dealer: str):
        """初始化记牌器"""
        self.dealer = dealer  # 庄家
        self.card_counts = self._initialize_card_counts()  # 牌数量统计
        self.player_discards = defaultdict(list)  # 玩家弃牌记录

    def _initialize_card_counts(self):
        """初始化所有牌的数量（每种牌4张）"""
        counts = defaultdict(int)

        # 添加万、条、饼花色（1-9）
        for suit in ['万', '条', '饼']:
            for num in range(1, 10):
                counts[f"{num}{suit}"] = 4

        # 添加字牌（东南西北中发白）
        for wind in ['东', '南', '西', '北']:
            counts[wind] = 4
        for dragon in ['中', '发', '白']:
            counts[dragon] = 4

        return counts

    def track_initial_hand(self, player: str, tiles: list):
        """跟踪玩家初始手牌"""
        for tile in tiles:
            self.card_counts[tile] -= 1

    def track_discard(self, player: str, tile: str):
        """跟踪玩家弃牌"""
        self.player_discards[player].append(tile)
        self.card_counts[tile] -= 1
        self.call_tracker_api(player, "discard", tile)

    def call_tracker_api(self, player: str, action: str, tile: str):
        """记牌器API调用接口"""
        # print(f"[记牌器API] 玩家: {player}, 动作: {action}, 牌: {tile}, 剩余数量: {self.card_counts[tile]}")

    def print_tracker_status(self):
        print("")
        # """打印当前记牌器状态"""
        # # 顶部标题
        # print("\n" + "=" * 70)
        # print("麻将记牌器".center(70))
        # print("=" * 70)
        #
        # # 玩家出牌记录区域
        # print("\n" + "-" * 70)
        # print("玩家出牌记录".center(70))
        # print("-" * 70)
        #
        # # 计算最长玩家名长度，用于对齐
        # max_name_len = max(len(player) for player in self.player_discards) if self.player_discards else 4
        #
        # # 打印每个玩家的出牌
        # for player in self.player_discards:
        #     # 玩家名右对齐
        #     player_label = f"{player}:".rjust(max_name_len + 1)
        #
        #     # 出牌记录，每8个牌换行
        #     discards = self.player_discards[player]
        #     if not discards:
        #         print(f"{player_label} 暂无出牌")
        #         continue
        #
        #     # 分块显示出牌记录
        #     chunks = [discards[i:i + 8] for i in range(0, len(discards), 8)]
        #     for i, chunk in enumerate(chunks):
        #         if i == 0:
        #             print(f"{player_label} {' '.join(chunk)}")
        #         else:
        #             print(f"{' ' * (max_name_len + 1)} {' '.join(chunk)}")
        #
        # # 剩余牌池区域
        # print("\n" + "-" * 70)
        # print("剩余牌池统计".center(70))
        # print("-" * 70)
        #
        # # 数字牌显示（万、条、饼）
        # print("\n" + "数字牌".center(70))
        # print("-" * 70)
        # suit_order = ['万', '条', '饼']
        # for suit in suit_order:
        #     # 构建该花色的所有牌
        #     suit_line = []
        #     for num in range(1, 10):
        #         tile = f"{num}{suit}"
        #         count = self.card_counts[tile]
        #         # 显示格式: "1万(2)"，使用2位数字显示数量
        #         if count > 0:
        #             suit_line.append(f"{num}{suit}({count:2d})")
        #
        #     # 分两列显示（1-5和6-9）
        #     col1 = " ".join(suit_line[:5])
        #     col2 = " ".join(suit_line[5:])
        #     print(f"{suit}牌:".ljust(8) + col1.ljust(40) + col2)
        #
        # # 字牌显示（风牌、箭牌）
        # print("\n" + "字牌".center(70))
        # print("-" * 70)
        #
        # # 风牌
        # winds = ['东', '南', '西', '北']
        # wind_line = []
        # for wind in winds:
        #     if self.card_counts[wind] > 0:
        #         wind_line.append(f"{wind}({self.card_counts[wind]:2d})")
        #
        # # 箭牌
        # dragons = ['中', '发', '白']
        # dragon_line = []
        # for dragon in dragons:
        #     if self.card_counts[dragon] > 0:
        #         dragon_line.append(f"{dragon}({self.card_counts[dragon]:2d})")
        #
        # # 风牌和箭牌分两列显示
        # print("风牌:".ljust(8) + " ".join(wind_line).ljust(30) +
        #       "箭牌:".ljust(8) + " ".join(dragon_line))
        #
        # # 底部边框
        # print("\n" + "=" * 70 + "\n")